#coding=utf-8

import threading,time
import dbmngr

class MyTimer(threading.Thread):
    def __init__(self,fn,args=(),sleep=0,lastDo=True, cycles=-1):
        threading.Thread.__init__(self)
        self.fn = fn
        self.args = args
        self.sleep = sleep
        self.lastDo = lastDo
        self.setDaemon(True)
         
        self.isPlay = True
        self.fnPlay = False
     
    def __do(self):
        self.fnPlay = True
        apply(self.fn,self.args)
        self.fnPlay = False
     
    def run(self):
        while self.isPlay :
            #time.sleep(self.sleep)
            self.__do()
            time.sleep(self.sleep)
     
    def stop(self):
        #stop the loop
        self.isPlay = False
        while True:
            if not self.fnPlay : break
            time.sleep(0.01)
        #if lastDo,do it again
        if self.lastDo : self.__do()
        
class MyEventTimer(MyTimer):
    def getExpiredEvent(self, now, last=None):
        sql = "select id,title,content,startDate from %s where startDate<='%s'"%('event', now)
        if (last is not None):
            sql += " and startDate>'%s'" %last 
             
        cnt = self.dbmngr.execute(sql)
        if (0 == cnt):
            return []
        
        return self.dbmngr.cursor.fetchall()
    
    def getExpiredNum(self, now, last=None):
        sql = "select count(*) from %s where startDate<='%s'"%('event', now)
        if (last is not None):
            sql += " and startDate>'%s'" %last 
             
        self.dbmngr.execute(sql)
        return self.dbmngr.cursor.fetchall()[0]
        
    def checkEvent(self):
        import datetime
        import product
        import wx
        
        now = datetime.datetime.now()
        
        # check expired event between last and now
        #list = product.CDataEvent.getExpiredEvent(now, self.last)
        list = self.getExpiredEvent(now, self.last)
        #self.win.setExpiredNum(len(list))
        #self.win.setExpiredNum(product.CDataEvent.getExpiredNum(now))
        self.win.setExpiredNum(self.getExpiredNum(now))
        
        # set last time
        self.last = now 
        
        if (list):
            msg = u'有提醒已到期，请及时处理：\n'
            index = 1
            for id,title,content,startDate in list:
                msg += str(index) + '. ' + title + '\n'
                index += 1
            
            dlg = wx.MessageDialog(self.win, msg, u'提醒到期',wx.OK)
            dlg.ShowModal()
        
        #print 'Expired event:%d' %(len(list))

    def __init__(self, win):
        MyTimer.__init__(self, self.checkEvent, sleep=60, lastDo=False)
        
        self.last = None
        
        self.win = win
        self.win.appendThread(self)
    
        self.dbmngr = dbmngr.Dbmngr()